package org.adorsys.aderp.orga.service;

import java.util.List;

import org.adorsys.aderp.orga.domain.OrgaAddressRole;
import org.adorsys.aderp.orga.domain.OrgaPerson;
import org.adorsys.aderp.orga.domain.PersonAddress;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;


public class PersonAddressServiceImpl implements PersonAddressService {

	@Override
	public List<PersonAddress> findByOrgaPerson(OrgaPerson orgaPerson) {
		return personAddressRepository.findByOrgaPerson(orgaPerson);
	}
    
    public void savePersonAddress(PersonAddress personAddress) {
    	OrgaPerson orgaPerson = personAddress.getOrgaPerson();
    	if(StringUtils.isBlank(personAddress.getPersonAddressKey())){
    		OrgaAddressRole addressRole = personAddress.getAddressRole();
    		personAddress.setPersonAddressKey(orgaPerson.getPersonNumber() +":"+addressRole.getAddressRoleKey() +":"+RandomStringUtils.randomNumeric(3));
    	}
    	// this is a dependent object of the person. So same record owner.
    	if(StringUtils.isBlank(personAddress.getRecordOwner())){
    		personAddress.setRecordOwner(orgaPerson.getRecordOwner());
    	}
        personAddressRepository.save(personAddress);
    }


    @Override
    public Page<PersonAddress> searchPersonAddress(OrgaPerson orgaPerson, OrgaAddressRole addressRole,Integer page, Integer size)
    {
		PageRequest pageable = new PageRequest(page, size);
		if(orgaPerson!=null && addressRole==null){
			return personAddressRepository.findByOrgaPerson(orgaPerson, pageable);
		} else if(orgaPerson!=null && addressRole!=null){
			return personAddressRepository.findByOrgaPersonAndAddressRole(orgaPerson, addressRole, pageable);
		} else if(orgaPerson==null && addressRole!=null){
			return personAddressRepository.findByAddressRole(addressRole, pageable);
		} else {
			return personAddressRepository.findAll(pageable);
		}
    }
}
